/**
 * IndexedDB 工具类
 * 用于自动保存和恢复表单数据
 */

const DB_NAME = 'JobWorthCalculator'
const DB_VERSION = 1
const STORE_NAME = 'formData'

interface FormDataStore {
  id: string
  formData: any
  timestamp: number
}

class IndexedDBUtils {
  private db: IDBDatabase | null = null

  // 初始化数据库
  async init(): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(DB_NAME, DB_VERSION)

      request.onerror = () => {
        console.error('IndexedDB 打开失败:', request.error)
        reject(request.error)
      }

      request.onsuccess = () => {
        this.db = request.result
        console.log('IndexedDB 初始化成功')
        resolve()
      }

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result
        
        // 创建对象存储空间
        if (!db.objectStoreNames.contains(STORE_NAME)) {
          const store = db.createObjectStore(STORE_NAME, { keyPath: 'id' })
          store.createIndex('timestamp', 'timestamp', { unique: false })
          console.log('IndexedDB 存储空间创建成功')
        }
      }
    })
  }

  // 保存表单数据
  async saveFormData(formData: any): Promise<void> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      if (!this.db) {
        reject(new Error('数据库未初始化'))
        return
      }

      const transaction = this.db.transaction([STORE_NAME], 'readwrite')
      const store = transaction.objectStore(STORE_NAME)

      const data: FormDataStore = {
        id: 'latest', // 始终使用相同的ID，保持只有一份最新数据
        formData: { ...formData },
        timestamp: Date.now()
      }

      const request = store.put(data)

      request.onsuccess = () => {
        console.log('表单数据已保存到 IndexedDB')
        resolve()
      }

      request.onerror = () => {
        console.error('保存表单数据失败:', request.error)
        reject(request.error)
      }
    })
  }

  // 恢复表单数据
  async getFormData(): Promise<any | null> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      if (!this.db) {
        reject(new Error('数据库未初始化'))
        return
      }

      const transaction = this.db.transaction([STORE_NAME], 'readonly')
      const store = transaction.objectStore(STORE_NAME)
      const request = store.get('latest')

      request.onsuccess = () => {
        const result = request.result
        if (result && result.formData) {
          console.log('从 IndexedDB 恢复表单数据')
          resolve(result.formData)
        } else {
          console.log('IndexedDB 中没有找到表单数据')
          resolve(null)
        }
      }

      request.onerror = () => {
        console.error('读取表单数据失败:', request.error)
        reject(request.error)
      }
    })
  }

  // 清除表单数据
  async clearFormData(): Promise<void> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      if (!this.db) {
        reject(new Error('数据库未初始化'))
        return
      }

      const transaction = this.db.transaction([STORE_NAME], 'readwrite')
      const store = transaction.objectStore(STORE_NAME)
      const request = store.delete('latest')

      request.onsuccess = () => {
        console.log('表单数据已从 IndexedDB 清除')
        resolve()
      }

      request.onerror = () => {
        console.error('清除表单数据失败:', request.error)
        reject(request.error)
      }
    })
  }

  // 关闭数据库连接
  close(): void {
    if (this.db) {
      this.db.close()
      this.db = null
      console.log('IndexedDB 连接已关闭')
    }
  }
}

// 创建单例实例
export const indexedDBUtils = new IndexedDBUtils()

// 导出类型
export type { FormDataStore }